package com.cardgame.controller;

import com.cardgame.dao.*;
import com.cardgame.model.card.*;
import com.cardgame.model.level.*;
import com.cardgame.model.deck.Deck;
import com.cardgame.model.deck.DeckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/api/battle")
public class BattleController {

    @Autowired
    private CardDao cardDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private ArchivalDao archivalDao;

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private BuffDao buffDao;

    private Level currentBattle;

    @Autowired
    private DeckService deckService;
    private LevelInfo currentLevelInfo;

    @GetMapping("/init-level")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> initLevel() {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取关卡信息
            Integer levelNumber = archivalDao.getArchival().getProgress();
            LevelInfo levelInfo = levelDao.getLevelById(levelNumber);
            if (levelInfo == null)
                throw new IllegalArgumentException("关卡不存在");
            currentLevelInfo = levelInfo;

            response.put("success", true);
            response.put("message", "关卡初始化成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "初始化关卡失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/init-random")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> initRandomMode() {
        Map<String, Object> response = new HashMap<>();
        try {
            currentLevelInfo = getRandomLevelInfo();

            response.put("success", true);
            response.put("message", "随机模式初始化成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "初始化随机模式失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    private LevelInfo getRandomLevelInfo() {
        List<Deck> allEnemyDecks = deckService.getAllDecks();
        if (allEnemyDecks.isEmpty())
            throw new IllegalStateException("没有可用的敌方卡组");

        // 随机选择一个敌方卡组
        Random random = new Random();
        Deck randomEnemyDeck = allEnemyDecks.get(random.nextInt(allEnemyDecks.size()));

        // 创建随机关卡信息
        LevelInfo randomLevelInfo = new LevelInfo();
        randomLevelInfo.setLevelNumber(-1); // 使用-1表示随机模式
        randomLevelInfo.setEnemyDeckId(randomEnemyDeck.getId());
        randomLevelInfo.setRewardGold(100); // 随机模式的基础奖励
        randomLevelInfo.setRewardExp(50);
        return randomLevelInfo;
    }

    @GetMapping("/battle-state")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getBattleState() {
        System.out.println("getBattleState");
        Map<String, Object> response = new HashMap<>();
        try {
            if (currentBattle == null) {
                throw new IllegalStateException("战斗未初始化");
            }
            // 获取战斗状态
            // 全局信息
            Map<String, Object> globalInfo = Map.of(
                    "currentRound", currentBattle.getRound()
            );

            // 敌方信息
            Map<String, Object> enemyInfo = Map.of(
                    "mainRole", currentBattle.getEnemyPlayer().getMainRole().toMap(),
                    "appearRoles", getAppearRolesMap(currentBattle.getEnemyPlayer().getAppearRoles()),
                    "handCardSize", currentBattle.getEnemyPlayer().getHandCards().size()
            );

            // 我方信息
            Map<String, Object> playerInfo = Map.of(
                    "mainRole", currentBattle.getSelfPlayer().getMainRole().toMap(),
                    "appearRoles", getAppearRolesMap(currentBattle.getSelfPlayer().getAppearRoles()),
                    "handCards", currentBattle.getSelfPlayer().getHandCards()
                            .stream().map(this::getCardMap).toList()
            );

            // 构建返回数据
            response.put("success", true);
            response.put("globalInfo", globalInfo);
            response.put("enemyInfo", enemyInfo);
            response.put("playerInfo", playerInfo);
            return ResponseEntity.ok(response);
        }
        catch (Exception e) {
            System.out.println("getBattleState error: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取战斗状态失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/enemy-deck")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getEnemyDeck() {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取敌方卡组信息
            Deck enemyDeck = archivalDao.getDeckById(currentLevelInfo.getEnemyDeckId());
            if (enemyDeck == null) {
                throw new IllegalArgumentException("敌方卡组不存在");
            }
            
            response.put("success", true);
            response.put("enemyDeck", enemyDeck);
            response.put("levelInfo", currentLevelInfo);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取敌方卡组失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/player-decks")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getPlayerDecks() {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取玩家所有卡组
            List<Deck> playerDecks = deckService.getAllDecks();
            
            response.put("success", true);
            response.put("playerDecks", playerDecks);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取玩家卡组失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/select-deck/{deckId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> selectDeck(@PathVariable Integer deckId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 初始化战斗
            currentBattle = new Level(cardDao, roleDao, archivalDao, buffDao);
            currentBattle.initMainRoles(deckId, currentLevelInfo.getEnemyDeckId());
            // 发牌
            currentBattle.SelfDealCards();
            currentBattle.EnemyDealCards();
            
            response.put("success", true);
            response.put("message", "选择卡组成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("selectDeck error: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "选择卡组失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/deal-cards")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> dealCards() {
        System.out.println("dealCards");
        Map<String, Object> response = new HashMap<>();
        try {
            if (currentBattle == null) {
                throw new IllegalStateException("战斗未初始化");
            }
            
            // 发牌
            currentBattle.SelfDealCards();
            currentBattle.EnemyDealCards();
            
            response.put("success", true);
            response.put("message", "发牌成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("dealCards error: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "发牌失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @PostMapping("/play-card")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> playCard(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (currentBattle == null) {
                throw new IllegalStateException("战斗未初始化");
            }
            
            Integer cardId = (Integer) request.get("cardId");
            Integer targetId = (Integer) request.get("targetId");
            System.out.println("playCard: " + cardId + " " + targetId);
            
            // 使用卡牌
            currentBattle.SelfUseCard(cardId, targetId != null ? targetId : 0);
            
            response.put("success", true);
            response.put("message", "卡牌打出成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("playCard error: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "卡牌打出失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/use-skill")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> useSkill() {
        Map<String, Object> response = new HashMap<>();
        try {
            if (currentBattle == null) {
                throw new IllegalStateException("战斗未初始化");
            }
            
            // 使用技能
            if (currentBattle.SelfUseSkill()){
                response.put("success", true);
                response.put("message", "技能使用成功");
            } else{
                response.put("success", false);
                response.put("message", "技能使用失败");
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("useSkill error: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "技能使用失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/end-turn")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> endTurn() {
        Map<String, Object> response = new HashMap<>();
        try {
            if (currentBattle == null) {
                throw new IllegalStateException("战斗未初始化");
            }
            
            // 玩家结束回合
            int result = currentBattle.SelfEndRound();
            
            // 如果战斗未结束，执行敌方回合
            if (result == 0) {
                currentBattle.EnemyUseCard();
                result = currentBattle.EnemyEndRound();
                result = -result;
            }
            
            Map<String, Object> battleResult = new HashMap<>();
            battleResult.put("isEnd", result != 0);
            battleResult.put("isVictory", result == 1);
            
            if (result != 0) {
                // 战斗结束，计算奖励
                if (result == 1 && currentLevelInfo != null) {
                    // 胜利时使用关卡配置的奖励
                    battleResult.put("rewards", Map.of(
                        "gold", currentLevelInfo.getRewardGold(),
                        "exp", currentLevelInfo.getRewardExp()
                    ));
                    archivalDao.getArchival().setProgress(currentLevelInfo.getLevelNumber() + 1);
                    archivalDao.getArchival().setMoney(archivalDao.getArchival().getMoney() + currentLevelInfo.getRewardGold());
                    archivalDao.saveArchival();
                    // 重置关卡信息
                    clearBattle();
                } else {
                    // 失败时没有奖励
                    battleResult.put("rewards", Map.of(
                        "gold", 0,
                        "exp", 0
                    ));
                    // 重置关卡信息
                    clearBattle();
                }
            }
            
            response.put("success", true);
            response.put("battleResult", battleResult);
            System.out.println("endTurn: " + response);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println("endTurn error: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "结束回合失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    @GetMapping("/clear-battle")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> clearBattle() {
        Map<String, Object> response = new HashMap<>();
        try {
            currentBattle = null;
            
            response.put("success", true);
            response.put("message", "清除战斗数据成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "清除战斗数据失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    private Map<String, Object> getCardMap(Card card) {
        switch (card) {
            case RoleCard roleCard -> {
                return roleCard.toMap();
            }
            case ActionCard actionCard -> {
                return actionCard.toMap();
            }
            case TotalWeaponCard totalWeaponCard -> {
                return totalWeaponCard.toMap();
            }
            case RoleWeaponCard roleWeaponCard -> {
                return roleWeaponCard.toMap();
            }
            default -> throw new IllegalArgumentException("Unknown card type");
        }
    }

    private List<Map<String, Object>> getAppearRolesMap(List<LevelRole> appearRoles) {
        List<Map<String, Object>> appearRolesInfo = new ArrayList<>();
        for (LevelRole role : appearRoles) {
            role.setFirstShow(false);
            Map<String, Object> roleInfo = role.toMap();
            roleInfo.put("id", appearRoles.indexOf(role));
            appearRolesInfo.add(roleInfo);
        }
        return appearRolesInfo;
    }
} 